package ar.edu.itba.it.paw.repo.impl;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import ar.edu.itba.it.paw.domain.User;
import ar.edu.itba.it.paw.domain.exceptions.RegisteredMailException;
import ar.edu.itba.it.paw.domain.exceptions.RegisteredUsernameException;
import ar.edu.itba.it.paw.repo.AbstractHibernateRepo;
import ar.edu.itba.it.paw.repo.UserRepo;

@Repository
public class HibernateUserRepo extends AbstractHibernateRepo implements UserRepo{

	@Autowired
	public HibernateUserRepo(SessionFactory sessionFactory){
		super(sessionFactory);
	}
	
	@Override
	public List<User> getAllUsers() {
		return find("from User");
	}

	@Override
	public User getUser(int user_id) {
		return get(User.class, user_id);
	}

	@Override
	public User getUser(String username) {
		try{
		return (User) getOne("from User as u where u.username = ?",username);
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public void addUser(User user) throws RegisteredUsernameException, RegisteredMailException{
		if(user == null)
			throw new IllegalArgumentException();
		
		if(!existsUser(user)){
			save(user);
		}
		else{
			if(existsMail(user.getMail())){
				throw new RegisteredMailException();
			}
			if(getUser(user.getUsername()) != null){
				throw new RegisteredUsernameException(); 
			}
		}
	}

	@Override
	public boolean authenticate(String username, String password) {
		if(username == null || password == null){
			throw new IllegalArgumentException("Null error");
		}
		if(getUser(username) == null){
			return false;
		}
		if(getUser(username).getPassword().equals(password)){
			return true;
		}
		return false;
	}
	
	public boolean existsUser(User user){
		if(user == null){
			throw new IllegalArgumentException("No se puede buscar un usuario nulo");
		}
		if(this.getUser(user.getUsername()) == null && !existsMail(user.getMail()) ){
			return false;
		}
		return true;
	}
	
	private boolean existsMail(String mail){
		if(mail == null){
			throw new IllegalArgumentException("No se puede buscar un mail nulo");
		}
		User user = getOne("from User as u where u.mail = ?", mail);
		if(user == null){
			return false;
		}
		return true;
	}
 
}
